<!--
* description: 财务管理-授信额度调整
* author: wangjuan
* createdDate: 2021-3-3
-->
<template>
  <div class="app-container app-container-table">
    <one-table-template
      ref="multipleTable"
      :key="oneTableKey"
      :dynamic-buttons="tableButtons"
      :dynamic-components="tableComponents"
      :dynamic-api-config="apiConfig"
      :dynamic-table-cols="tableCols"
      :dynamic-form-fields="formField"
      :dynamic-is-show-more-btn="true"
      :dynamic-is-show-select="true"
      :dynamic-is-init-table="true"
      :callback-obj="callbackObj"
    />
  </div>
</template>
<script>

import { oneTableWithViewTemplateMixins } from '@/components/mixins/oneTableWithViewTemplateMixins'
import OneTableTemplate from '@/components/templates/oneTable'
import Vue from 'vue'
import api from '@/api/pa/financialManagement'

export default {
  name: 'CreditLineAdjustment',

  components: {
    OneTableTemplate
  },

  // 组件混入对象
  mixins: [oneTableWithViewTemplateMixins],

  // 阻塞路由预加载网格中组件的数据
  beforeRouteEnter(to, from, next) {
    Vue.prototype.$ConfigCache.CacheConfig.initData([to.path, ''], function() {
      next()
    })
  },

  data() {
    // 页面标识（与上面beforeRouteEnter中的对应）
    const viewPageCode = this.$route.path
    // 绑定事件配置化事件
    this.$ConfigCache.CacheConfig.bindEvent(this, [viewPageCode])

    return {
      // 网格查询API配置对象
      apiConfig: api.creditQueryByPage,
      rowData: {},
      selectData: [],
      updateTime: '',
      // 动态组件-按钮
      tableButtons: [
        {
          compKey: 'btnKey0',
          type: 'primary',
          size: 'small',
          name: 'preservation',
          clickEvent: () => this.save(),
          text: '保存'
        },
        {
          compKey: 'btnKey1',
          size: 'small',
          name: 'submissionUp',
          icon: 'iconfont  icon-submissionUp',
          clickEvent: () => this.submit(),
          disabled: true,
          text: '提交',
          position: 'left'
        },
        {
          compKey: 'btnKey6',
          size: 'small',
          name: 'reset',
          clickEvent: () => {
            this.$refs['multipleTable'].queryTable(null, null, null, null, null, { formField: {}})
          },
          text: '刷新'
        },
        // {
        //   compKey: 'btnKey6',
        //   size: 'small',
        //   name: 'submissionUp',
        //   icon: 'iconfont  icon-submissionUp',
        //   clickEvent: () => this.window.location.reload(),
        //   disabled: true,
        //   text: '刷新',
        //
        // },
        {
          compKey: 'btnKey2',
          size: 'small',
          name: 'reset',
          clickEvent: () => this.resets(),
          text: this.$t('sys.button.reset')
        },
        {
          compKey: 'btnKey3',
          size: 'small',
          name: 'cancel',
          clickEvent: () => this.invalid(),
          text: '作废',
          position: 'left',
          disabled: true
        },
        {
          compKey: 'btnKey4',
          size: 'small',
          name: 'importTemplate',
          icon: 'iconfont icon-importTemplate',
          clickEvent: () => this.handFileListChange(),
          text: '导入',
          position: 'upload'
        },
        {
          compKey: 'btnKey5',
          type: 'text',
          size: 'small',
          name: 'importTemplateDownload',
          icon: 'iconfont  icon-importTemplateDownload',
          click: () => this.templateDownload(),
          text: 'Excel导入模板下载',
          position: 'left'
        }
      ],

      // 动态组件-查询条件
      tableComponents:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
          .tableComponents.length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path]
            .tableComponents
          : [
            {
              compKey: 'compKey2',
              labelName: '网点编码：',
              codeField: 'dlrCode',
              textField: 'dlrType',
              component: () => import('@/components/pa/dlrCode'),
              type: 'inputText',
              // isRequire: true,
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey1',
              labelName: '网点类型：',
              codeField: 'dlrType',
              component: () => import('@/components/org/commonSelect'),
              oFields: 'dlrType,dlrTypeCn',
              customObj: {
                api: {
                  APIUrl: 'mp/e3sh/spareparts/finance/partDiscountSettingDlrService/queryDlrTypes.do'
                },
                listQuery: {
                  dlrType: ''
                },
                selectType: '1'
              },
              type: 'dropdownList',
              disabled: true,
              isRequire: true,
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey3',
              labelName: '网点名称：',
              codeField: 'dlrShortName',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              disabled: true,
              isRequire: true,
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey4',
              labelName: '授信额度：',
              codeField: 'creditQuota',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isRequire: true,
              validrule: {
                resectMessage: {
                  isformat: '请输入正确的额度!'
                },
                // isformat: /^([1-9]\d{0,10}|[1-9][0-9]{0,10}\.\d{1,2}|0\.\d{1,2}?|0)$/
                isformat: /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/
              },
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey5',
              labelName: '提交日期：',
              codeField: 'quotaSubmitDate',
              component: () => import('@/components/org/datePicker/datePicker'),
              type: 'datePicker',
              disabled: true,
              isRequire: true,
              isMul: false,
              isMust: true
            },
            {
              compKey: 'compKey6',
              labelName: '备注：',
              codeField: 'remark',
              component: () => import('@/components/org/commonInput'),
              type: 'inputText',
              isMul: false,
              isMust: true
            }
          ],

      // 动态生成网格列
      tableCols:
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path] &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols &&
        this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          .length > 0
          ? this.$ConfigCache.CacheConfig.cacheData[this.$route.path].tableCols
          : [
            {
              prop: 'accountReviewId',
              label: '审核ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'updateControlId',
              label: '并发控制ID',
              hidden: true,
              alwaysHidden: true
            },
            {
              prop: 'dlrCode',
              label: '网点编码'
            },
            {
              prop: 'dlrShortName',
              label: '网点名称'
            },
            {
              prop: 'dlrTypeName',
              label: '网点类型'
            },
            {
              prop: 'creditQuota',
              label: '授信额度'
            },
            {
              prop: 'quotaSubmitDate',
              label: '提交日期'
            },
            {
              prop: 'reviewStatusName',
              label: '状态'
            },
            {
              prop: 'remark',
              label: '备注'
            }
          ],

      // 表单查询数据
      formField: this.$utils.getFormField(this, {
        dlrType: '',
        dlrCode: '',
        dlrShortName: '',
        creditQuota: '',
        quotaSubmitDate: '',
        remark: '',
        dlrId: '',
        accountReviewId: '',
        updateControlId: ''
      }, this.$ConfigCache.CacheConfig.cacheData[viewPageCode]),

      // 单表格模版页面组件回调事件
      callbackObj: {
        onCheckSelectChange: (selection) => {
          this.selectData = selection

          this.handleSelectionChange(selection)
        },

        onRowDbClick: this.rowClickModel
      }
    }
  },

  mounted() {
    // 总部为空 自选     网点账号：禁用搜索框 查当前网点
    if(this.$store.getters.orgInfo.DLR_ID === "HOST"){
      this.formField.dlrCode = ''
      this.tableComponents[0].disabled = false
    } else {
      this.getType()
      this.formField.dlrCode = this.$store.getters.orgInfo.DLR_CODE
      this.formField.dlrShortName = this.$store.getters.orgInfo.DLR_NAME
      this.formField.dlrId = this.$store.getters.orgInfo.DLR_ID
      this.tableComponents[0].disabled = true
    }
    this.tableComponents[0].compKey = this.tableComponents[0].compKey+"1"

      
    // 列表查询
    this.queryTable(1)
    this.addDate()
  },

  methods: {
    // 获取当前年月日
    addDate() {
      const nowDate = new Date()
      const date = {
        year: nowDate.getFullYear(),
        month: nowDate.getMonth() + 1,
        date: nowDate.getDate()
      }
      const newmonth = date.month > 10 ? date.month : '0' + date.month
      const day = date.date > 10 ? date.date : '0' + date.date
      this.formField.quotaSubmitDate = date.year + '-' + newmonth + '-' + day
    },

    rowClickModel(row) {
      this.rowData = row
      this.formField.dlrType = row.dlrType
      this.formField.dlrCode = row.dlrCode
      this.formField.dlrShortName = row.dlrShortName
      this.formField.creditQuota = row.creditQuota
      this.formField.quotaSubmitDate = row.quotaSubmitDate
      // this.formField.updateTime = row.updateTime
      this.formField.remark = row.remark
      this.formField.dlrId = row.dlrId
      this.formField.accountReviewId = row.accountReviewId
      this.formField.updateControlId = row.updateControlId
    },
    resets() {
      // for (const attr in this.formField) {
        // 不重置时间
        // if (attr !== 'quotaSubmitDate') {
        //   this.formField[attr] = ''
        // }
      // }

      this.formField.creditQuota=""
      this.formField.remark=""
      // this.formField.dlrId=""
      this.formField.accountReviewId=""
      this.formField.updateControlId=""
      // 总部则清空
      if(this.$store.getters.orgInfo.DLR_ID === "HOST"){
        this.formField.dlrCode=""
        this.formField.dlrType=""
        this.formField.dlrShortName=""
        this.formField.dlrId=""
      }
      
      this.resetIconv()
    },
    resetIconv() {
      this.$nextTick(() => {
        for (const attr in this.$refs['multipleTable'].$refs) {
          if (attr.startsWith('true')) {
            this.$refs['multipleTable'].$refs[attr][0].$children[0].$children[2].iconV = ''
          }
        }
      })
    },

    // 保存
    save() {
      this.$utils.validataMoth(this, 'validpage')
      if (!this.valid) return
      const that = this
      const queryObj = {
        apiConfig: api.creditSave,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: that.formField
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message('保存成功')
          this.resets()
          that.$refs['multipleTable'].queryTable()
        } else {
          this.$message({
            message: response.msg,
            type: 'warn',
            duration: 1000
          })
        }
      })
    },

    // 提交
    submit() {
      const that = this
      const datas = []
      this.selectData.forEach((val, index) => {
        datas.push({
          dlrType: val.dlrType,
          dlrCode: val.dlrCode,
          dlrShortName: val.dlrShortName,
          creditQuota: val.creditQuota,
          quotaSubmitDate: val.quotaSubmitDate,
          remark: val.remark,
          dlrId: val.dlrId,
          accountReviewId: val.accountReviewId,
          updateControlId: val.updateControlId
        })
      })
      const queryObj = {
        apiConfig: api.creditSubmit,
        // 条件/实体参数（变量），根据typeParam中的定义配置
        variables: {
          // 当前中台使用的名称有dataInfo、info，具体查看API文档
          dataInfo: datas
        }
      }
      // 转换了中台请求格式数据
      var paramD = that.$getParams(queryObj)
      // 调用中台API方法（可复用）
      that.$requestAPI(paramD).then((response) => {
        if (response.result === '1') {
          this.$message('提交成功！')
          that.$refs['multipleTable'].queryTable(null, null, null, null, null, { formField: {}})
        } else {
          this.$message(response.msg || '提交失败!')
        }
      })

      // this.$refs['multipleTable'].list = []
    },

    // 作废
    invalid() {
      // debugger
      // const that = this
      this.$confirm('确定要作废吗?', '提示', {
        type: 'warning'
      }).then(() => {
        const datas = []
        this.selectData.forEach((val, index) => {
          datas.push({
            dlrType: val.dlrType,
            orgTypeName: val.orgTypeName,
            dlrCode: val.dlrCode,
            dlrShortName: val.dlrShortName,
            creditQuota: val.creditQuota,
            quotaSubmitDate: val.quotaSubmitDate,
            remark: val.remark,
            dlrId: val.dlrId,
            accountReviewId: val.accountReviewId,
            updateControlId: val.updateControlId
          })
        })
        const queryObj = {
        // 保存需要传 type="mutation"
          type: 'mutation',
          apiConfig: api.creditInvalid,
          // 条件/实体参数（变量），根据typeParam中的定义配置
          variables: {
            dataInfo: datas
          }
        }
        // 转换了中台请求格式数据
        var paramD = this.$getParams(queryObj)
        this.$requestAPI(paramD).then((response) => {
          if (response.result === '1') {
            this.$message('已成功作废！')
            this.$refs['multipleTable'].queryTable()
          } else {
            this.$message({ message: response.msg })
          }
        })
      }).catch(err => {
        console.log(err)
      })
    },

    // 导入
    handFileListChange(file, fileList) {
      if (this.beforeAvatarUpload(file)) {
        this.handleChange(file)
      }
    },
    beforeAvatarUpload(file) {
      if (file.size > 50 * 1024 * 1024) {
        this.$message({
          message: '文件大小不能超过50M',
          type: 'warning'
        })
        return false
      }
      const fileType = file.name.substr(file.name.lastIndexOf('.') + 1)
      if (fileType !== 'xls' && fileType !== 'xlsx') {
        this.$message({
          message: '只能导入后缀为xls,xlsx的文件！',
          type: 'warning'
        })
        return false
      }
      return true
    },
    handleChange(param) {
      const loading = this.$loading({
        lock: true,
        text: '导入中...',
        background: 'rgba(0, 0, 0, 0.5)'
      })
      const that = this
      const url = api.creditBeachImport.APIUrl
      that.$requestUpload(url, param).then(response => {
        if (response.result === '1') {
          this.$message('导入成功！')
          this.$refs['multipleTable'].queryTable(1)
        } else {
          this.$message({
            message: response.msg,
            type: 'warning'
          })
        }
      })
        .catch(_ => {})
        .finally(() => {
          loading.close()
        })
    },

    // 模板下载
    templateDownload() {
      this.$requestAPI({
        variables: { dataType: 'excel' },
        apiUrl: api.creditDownloadTemplate.APIUrl
      }).then(res => {
        this.$utils.downloadFile(res, 'excel导入模板下载.xlsx')
      })
    },

    // 当选择项发生变化时会触发该事件
    handleSelectionChange(selection) {
      const btns = this.tableButtons.filter(o => o.disabled !== undefined)
      if (btns.length > 0) {
        const isCheck = selection && selection.length > 0
        btns.forEach((item) => {
          item.disabled = !isCheck
        })
      }
    },

    // 网点类型获取
    getType(){
      const that=this
      this.$requestAPI({
        apiUrl: api.queryOrgDlrCodes.APIUrl,
        variables: {
          dlrCode: this.$store.getters.orgInfo.DLR_CODE,
          dlrId: "",
          dlrShortName: "",
        }
      }).then(res => {
        if (res.result === '1') {
          that.formField.dlrType = res.rows[0].dlrType === "1" ? "直营店" : "授权店"
        }
      })
    }
  }
}
</script>
